/*******************************************************************************
 * Copyright (c) 2008 Sylvain Sicard.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v2.1
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Sylvain Sicard - initial API and implementation
 ******************************************************************************/
package fr.jade.fraclite.orb.names;

import org.objectweb.naming.Binder;
import org.objectweb.naming.Name;
import org.objectweb.naming.NamingContext;
import org.objectweb.naming.NamingException;

public class AbstractName implements Name {

  protected static final String NAME_SEPAR = "::";
  
  protected long itfId;
  
  protected String signature;
  
  protected Binder naming;
  
  public AbstractName(long itfId, String signature, Binder naming){
    this.itfId = itfId;
    this.signature = signature;
    this.naming = naming;
  }
  
  public AbstractName(Name n, Binder naming){
    this( ((AbstractName)n).getItfId(),
                  ((AbstractName)n).getSignature(),
                  ((AbstractName)n).getNaming());
  }
  
  public AbstractName(byte[] n, Binder naming){
    this.naming = naming;
    String name = new String(n);
    String[] values = name.split(NAME_SEPAR);
    signature = values[0];
    itfId = Long.parseLong(values[1]);
  }
  @Override
  public byte[] encode() throws NamingException {
    String name = signature+NAME_SEPAR+String.valueOf(itfId);
    return name.getBytes();
  }

  @Override
  public NamingContext getNamingContext() {
    return naming;
  }

  @Override
  public boolean equals(Object o){
    if(o instanceof TcpIpName){
      return ((TcpIpName)o).getNamingContext().equals(naming) &&
             ((TcpIpName)o).getItfId() == itfId;
    }else{
      return false;
    }
  }

  protected long getItfId() {
    return itfId;
  }

  public String getSignature(){
    return signature;
  }
  
  protected Binder getNaming() {
    return naming;
  }
  
  protected byte[] concat(byte[] t1, byte[] t2){
    byte[] res = new byte[t1.length+t2.length];
    int i=0;
    for(byte b : t1){
      res[i++]=b;
    }
    for(byte b : t2){
      res[i++]=b;
    }
    return res;
  }
}
